package com.pdd.rabbitmq.web;

import com.pdd.rabbitmq.config.MessageQueueConfig;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author:liyangpeng
 * @date:2020/4/17 13:51
 */
@RestController
@Slf4j
@RequestMapping("/rabbitmq")
public class DelayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/message")
    public String send(String message,Integer delay){
        log.info("消息已发送:{},delay:{}",message,delay);
        rabbitTemplate.waitForConfirms(3000);
        rabbitTemplate.waitForConfirmsOrDie(3000);
        rabbitTemplate.convertAndSend(MessageQueueConfig.ORDER_EXCHANGE_NAME, MessageQueueConfig.QUEUE_ROUTING_KEY,message, a->{
            a.getMessageProperties().setHeader("1","3");
            a.getMessageProperties().setHeader("2","4");
            a.getMessageProperties().setDelay(delay);
            return a;
        });
        return "success";
    }

    @RabbitListener(queues = MessageQueueConfig.ORDER_QUEUE_NAME)
    public void consumer(Message message, Channel channel) throws IOException {
        String text=new String(message.getBody());
        log.info("消息开始消费:{},delay:{}",text,message.getMessageProperties().getDelay());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
